import random

from rest_framework.views import APIView
from celery_tasks.sms.yuntongxun.ccp_sms import CCP
from rest_framework.response import Response

# Create your views here.
from django_redis import get_redis_connection


class SMSCodeView(APIView):
    '''
    短信验证码
    '''

    def get(self, request, mobile):
        # 建立redis链接
        conn = get_redis_connection('verify')
        # 获取标志数据
        flag_data = conn.get('flag_%s' % mobile)
        if flag_data:
            return Response({'success': False, 'message':'请求过于频繁'}, status=400)

        # 生成及保存短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        pipe = conn.pipeline()
        pipe.setex('sms_%s' % mobile, 300, sms_code)
        pipe.setex('flag_%s' % mobile, 60, 'flag_data')
        pipe.execute()
        # 发送短信
        CCP().send_template_sms(mobile, [sms_code, 5], 1)
        print('短信验证码', sms_code)

        return Response({'success': True, 'sms_code': sms_code, 'message': '发送成功'})